from django.http import HttpResponseRedirect, HttpResponse, HttpResponseNotFound, HttpResponseNotAllowed
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login as auth_login, logout as auth_logout, authenticate
from django.contrib.auth.models import User
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.forms import AuthenticationForm
from forms import RegistrationForm
from models import *

def index(request):
	if request.user:
		return HttpResponseRedirect('/societies')
	else:
		return HttpResponseRedirect('/accounts/login')


def login(request):
	if request.user.is_authenticated():
		return HttpResponseRedirect('/accounts/profile')
	
	nextpage = request.GET.get('next', '/')
	auth_form = AuthenticationForm(None, request.POST or None)
	
	if auth_form.is_valid():
		auth_login(request, auth_form.get_user())
		return HttpResponseRedirect(nextpage)
	
	return render_to_response('accounts/login.html', {'form':auth_form}, context_instance=RequestContext(request))


def logout(request):
	auth_logout(request)
	return HttpResponseRedirect('/')


def register(request):
	if request.user.is_authenticated():
		return HttpResponseRedirect('/accounts/profile')
	
	register_form = RegistrationForm(request.POST or None)
	
	if register_form.is_valid():
		username = register_form.cleaned_data['username']
		password = register_form.cleaned_data['password1']
		email = register_form.cleaned_data['email']
		user = User.objects.create_user(username, email, password)
		
		user.first_name = register_form.cleaned_data['first_name']
		user.last_name = register_form.cleaned_data['last_name']
		
		user.save()
		user = authenticate(username=username, password=password)
		
		message = '<strong>Your account was created successfully</strong>, welcome to your new account!'
		
		return HttpResponseRedirect('/accounts/profile')
	
	return render_to_response('accounts/register.html', {'form':register_form}, context_instance=RequestContext(request))

@login_required()
def profile(request):
	return render_to_response('accounts/profile.html', context_instance=RequestContext(request))